/**
 * @file
 * @author  michal.nezerka@gmail.com
 * @brief   Application Class Implementation
 */

#include <iostream>
#include <wx/stdpaths.h>

#include "app.h"

using namespace wildwood;

// --------- AppSettings -------------------------------------
AppSettings::AppSettings() : mDbPath(wxT("")), mDefaultPos(0, 0), mLastPos(0, 0), mDefaultZoom(0)
{
    mDbPath = wxStandardPaths::Get().GetDocumentsDir() + wxT("wildwood.wwdb");
}

void AppSettings::LoadFromConfig(wxConfig *config)
{
    wxString c;

    // db path
    if (config->Read(wxT("global/db-path"), &c))
        mDbPath = c;

    double d;
    if (config->Read(wxT("global/default-pos-lat"), &d))
        mDefaultPos.setLat(d);
    if (config->Read(wxT("global/default-pos-lon"), &d))
        mDefaultPos.setLon(d);
    if (config->Read(wxT("global/last-pos-lat"), &d))
        mLastPos.setLat(d);
    if (config->Read(wxT("global/last-pos-lon"), &d))
        mLastPos.setLon(d);
    int i;
    if (config->Read(wxT("global/default-zoom"), &i))
        mDefaultZoom = i;
}

void AppSettings::SaveToConfig(wxConfig *config)
{
    config->Write(wxT("global/db-path"), mDbPath);
    config->Write(wxT("global/default-pos-lat"), mDefaultPos.getLat());
    config->Write(wxT("global/default-pos-lon"), mDefaultPos.getLon());
    config->Write(wxT("global/last-pos-lat"), mLastPos.getLat());
    config->Write(wxT("global/last-pos-lon"), mLastPos.getLon());
    config->Write(wxT("global/default-zoom"), mDefaultZoom);
}

// --------- App ---------------------------------------------

IMPLEMENT_APP(App);

bool App::OnInit()
{
    // initialize image handlers (for JPG, PNG, ... support)
    wxInitAllImageHandlers();

    wxHTTP::Initialize();

    // load and initialize configuration data
    config = new wxConfig(wxT("WildWood"));

    // load application settings
    mSettings = new AppSettings();
    mSettings->LoadFromConfig(config);

    // initialize logging
    wxLog::SetActiveTarget(new wxLogStderr());
    wxLog::SetLogLevel(wxLOG_Debug);

    //-----------------------------------------------------------------
    // open main window (frame)
    mFrame = new MainWnd(0L, wxT("WildWood"));
    mFrame->Show();

    return true;
}

int App::OnExit()
{
    wxLogDebug(wxT("Exiting application"));

    // save settings
    mSettings->SaveToConfig(config);
    delete mSettings;
    delete config;

    return wxApp::OnExit();
}

wxLog* App::CreateLogTarget()
{
    return new wxLogStderr();
}

void App::info(wxString fmt, ...)
{
    if (!mFrame)
        return;

    wxString infoText;

    va_list argptr;
    va_start(argptr, fmt);
    infoText.PrintfV(fmt, argptr);
    va_end(argptr);

    mFrame->addInfo(infoText);
}

